# Code for Table M3: Balance, Missing magistrates

rm(list = ls())

## ---------------------------------------
## Load Packages 
## ---------------------------------------
require('dplyr')
require('data.table')
require('gtools')

## ---------------------------------------
## Load Data and Functions
## ---------------------------------------
# load main dataset
load("../data0812.RData")

# load data with missing magistrates
load("../data0812Missing.RData")


directory <- "../functions/"
functions <- list.files(directory)  
loadfunctions <- sapply(functions, FUN = function(x)source(paste0(directory, x)))

## ---------------------------------------
#  Select Last Case Before Election
## ---------------------------------------
data0812 <- lastCase(data0812)

## ---------------------------------------
# create split variable
data0812$missingJudge <- 0
missing$missingJudge <- 1

# create weekend/weekday 
data0812$weekend <- ifelse(data0812$court_dow %in% c(4,2), 1, 0)
data0812$weekday <- ifelse(data0812$weekend == 0, 1, 0)
missing$weekday <- ifelse(missing$weekend == 0, 1, 0)

# combine
dta <- smartbind(data0812, missing)

# construct indicators

dta$shift1 <- ifelse(dta$court_shift == 1, 1, 0)
dta$shift2 <- ifelse(dta$court_shift == 2, 1, 0)
dta$shift3 <- ifelse(dta$court_shift == 3, 1, 0)

dta$Black <- ifelse(dta$race == "Black", 1, 0)
dta$White <- ifelse(dta$race == "White", 1, 0)
dta$Race_Other <- ifelse(dta$race == "Other", 1, 0)
dta$Race_Unk <- ifelse(dta$race == "Unknown", 1, 0)

# Balance test variables
outcomes <- c("age_2012", "Male", "Black", "White","Race_Other", "Race_Unk",
  "any_drug_2" ,  "any_violent_2", "fire_arms_2",   "any_rob_2" , "any_dui_2" , "totOGS" ,
  "prior_offender_2" ,
 "weekday", "weekend", 
  "shift1", "shift2", "shift3")

dta$split <- dta$missingJudge
set.seed(3105)
balance.tests <- runTTests(data = dta,  outcome.var.names = outcomes, indp.var = "split")
balance.tests <- as.data.frame(balance.tests)

balance.tests[,c(2:ncol(balance.tests))] <- sapply(balance.tests[,c(2:ncol(balance.tests))], as.numeric)
balance.tests[,c(2:ncol(balance.tests))] <- sapply(balance.tests[,c(2:ncol(balance.tests))], round, 2)

#Difference 
balance.tests$diffMeans <- balance.tests$mean_missing_judge - balance.tests$mean_judge

#Adjust for multiple tests
balance.tests$p_value_adjusted <- NA
balance.tests$p_value_adjusted <- p.adjust(as.numeric(balance.tests$p_value, method ="fdr"))

balance.tests <- subset(balance.tests, select=c(outcome:mean_missing_judge, diffMeans,
                                                p_value_adjusted))
cat("\nPrinting Table M3: Balance Missing Magistrate...\n")
print(balance.tests)
